'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //登录
    async login() {
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username && password){
            let hmcPwd = ctx.helper.hmc(password);
            let target = await service.user.login(username,hmcPwd);

            if(target.length){
                //生成token‘
                let token = jwt.sign({username,role_id:target[0].role_id},'lixd',{expiresIn:60*60*1});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    role_name:target[0].role_name
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'参数有误'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //注册
    async registry(){
        let {ctx,service} = this;
        let {username,password,role_name,role_id} = ctx.request.body;

        if(username && password && role_name && role_id){
            //1.查询此人是否存在
            let target = await service.user.selectUser(username);

            if(target.length){
                ctx.body = {
                    code:4,
                    msg:'此用户名已存在'
                }
            }else{
                let hmcPwd = ctx.helper.hmc(password);
                try{
                    //2.注册功能
                    await service.user.registry(username,hmcPwd,role_name,role_id);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:'注册失败'
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }

    }
}

module.exports = UserController;
